package org.com.suit.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.com.suit.common.LogInfo;
import org.com.suit.dao.RegistDao;
import org.com.suit.domain.Relation;
import org.com.suit.domain.Member;
import org.com.suit.exception.LoginErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class UserController {
	
	@Autowired
	Member member;
	
	@Autowired
	RegistDao dao;
	
	
	/* メインログイン画面へ */
	@RequestMapping(value="/mainLogin.do")
	public String mainHome() {
		
		return "mainLogin";
	}
	
	/* メインホームへ */
	@RequestMapping("/mainHome.do")
	public String mainBrowser() {
		
		return "mainHome";
	}
	
	/* ユーザー入会画面へ　*/
	@RequestMapping(value="/regUser.do")
	public String regUser() {
		
		return "userRegForm";
	}
	
	/* ユーザー登録を行う */
	@RequestMapping(value="/regUserSend.do", method=RequestMethod.POST)
	public String regUserSend(@ModelAttribute Member user){
		
		dao.addUser(user);
		
		return "mainLogin";
	}
	
	/* ログイン */
	@RequestMapping(value="/logIn.do", method=RequestMethod.POST)
	public String logIn(@RequestParam String name, String password, HttpSession session) throws LoginErrorException{
			
		Map<String, String> myInfo = new HashMap<String, String>();

		member = dao.findUserByName(name);
			
			if(name==""||password==""){
				throw new LoginErrorException("名前又パスワードを入力してください。");
			}
		
			if(member == null){
				throw new LoginErrorException("該当する名前を見つかりませんでいた。");
			}else if(!member.getPassword().equals(password)){
				throw new LoginErrorException("パスワードを確認してください。");
			}
					
		myInfo.put("no", Integer.toString(member.getNo()));	
		myInfo.put("name", member.getName());
		myInfo.put("password", password);
		
		session.setAttribute("myInfo", myInfo);
		LogInfo.getLogInfo(myInfo, member.getName()+"_login_success");
		
		return "redirect:readWritingLists.do";
	}
	
	/* メンバ目録一覧 */
	@RequestMapping("/allUserList.do")
	public String memberList(){
		
		return "allUserList";
	}
	
	/* ログアウト */
	@RequestMapping(value="logOut.do")
	public String logOut(HttpSession session){
		
		session.removeAttribute("myInfo");
		
		return "redirect:mainLogin.do";
	}
	
	/* 自分の情報を読み込み */
	@RequestMapping(value="/myInfo.do")
	public String myInfo(@RequestParam String name, Model model) {
		
		member = dao.findUserByName(name);
		
		model.addAttribute("currentUser", member);
		
		return "myInfo";
	}
	
	/* 自分の情報をupdate */
	@RequestMapping(value="/userUpdate.do", method=RequestMethod.POST)
	public String updateUserInfo(@ModelAttribute Member user) {
		
		dao.updateUser(user);
		
		return "redirect:mainLogin.do";
	}
	
	/* ユーザー脱退する */
	@RequestMapping(value="/userWithDraw.do", method=RequestMethod.GET)
	public String withDrawUser(@RequestParam Integer no) {
		
		dao.deleteUser(no);
		
		return "redirect:logOut.do";
	}
			
	/* Error 画面へ */
	@RequestMapping("/error.do")
	public String error() {
		
		return "loginError";
	}
	
	/* addFollowing */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/addFollowing.do")
	public void addFollowing(@RequestParam int num, HttpSession session, HttpServletResponse response) throws IOException {
		
		HashMap<String, String> map = new HashMap<String, String>();
		String name = null;
		
		map = (HashMap) session.getAttribute("myInfo");
		int no = Integer.valueOf(map.get("no"));
		name = dao.getUserName(num);
			
		Relation rel = new Relation();
		rel.setNo(no);
		rel.setFollowingNo(num);
		rel.setFollowingName(name);
		dao.addFollowing(rel);
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print("Following SUCCESS");
						
	}
	
	/* cancel Following */
	@RequestMapping("/cancelFollowing.do")
	public void cancelFollowing(@RequestParam int num, HttpServletResponse response) throws IOException{
		
		dao.cancelFollowing(num);
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print("UnFollowing SUCCESS");
	}
	

	/* JSON ユーザーリスト */
	@RequestMapping(value="/getJsonUserList.do")
	public void getJsonUserList(@RequestParam Integer num, HttpServletResponse response) throws IOException {
		
		JSONObject obj = new JSONObject();
		JSONObject userListObj;
		JSONObject relListObj;
		JSONArray arrUserList;
		JSONArray arrRelList;
		List<Member> userList;
		List<Relation> relList;
		
		userList = dao.getUserList();
			if(userList != null){
				userListObj = new JSONObject();
				arrUserList = new JSONArray();
					for(int i=0; i<userList.size(); i++){
						userListObj.put("no", userList.get(i).getNo());
						userListObj.put("name", userList.get(i).getName());
						userListObj.put("address", userList.get(i).getAddress());
						userListObj.put("birth", userList.get(i).getBirth());
						userListObj.put("email", userList.get(i).getEmail());
						arrUserList.add(userListObj);
					}
				obj.put("userList", arrUserList);
			}else{
				userList = new ArrayList<Member>();
			}
			
		relList = dao.getRelationInfo(num);
			if(relList != null){
				relListObj = new JSONObject();
				arrRelList = new JSONArray();
					for(int j=0; j<relList.size(); j++){
						relListObj.put("no", relList.get(j).getNo());
						relListObj.put("followingNo", relList.get(j).getFollowingNo());
						relListObj.put("followingName", relList.get(j).getFollowingName());
						arrRelList.add(relListObj);
					}
				obj.put("relList", arrRelList);
			}else{
				relList = new ArrayList<Relation>();
			}
		LogInfo.getLogInfo(relList, "relation_list");
			
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(obj.toString());
		
	}
	

}
